# test connect hardware:
import sensor, image, lcd, time
import gc, sys

from Maix import GPIO
from fpioa_manager import fm
from machine import UART

# config change for youself
UART_TX = 24  # 6 24
UART_RX = 25 # 7 25
api_run = 0
data_send= ''

img_size = [224,224]
board_cube = 1
index = 1

def send(uart_A=None,key_enter=1,key_back=1,key_next=1):
    global data_send , index
    #print("key data:", str(key_next.value() ))
    read_data = uart_A.read()
    if not read_data is None:
        print("recv = ", read_data)
    if key_enter.value() == 0 :
        index = index +1
        data_send = 'no:'+ str(index)
        print("enter send data:",data_send)
        uart_A.write('A')
        time.sleep_ms(100)
    if key_back.value() == 0 :
        index = index +1
        data_send = 'no:'+ str(index)
        print("back send data:",data_send)
        uart_A.write('B')
        time.sleep_ms(100)
        #close()
    if key_next.value() == 0 :
        index = index +1
        data_send = 'no:'+ str(index)
        print("next send data:",data_send)
        uart_A.write('face')
        time.sleep_ms(100)

def lcd_show_except(e):
    import uio
    err_str = uio.StringIO()
    sys.print_exception(e, err_str)
    err_str = err_str.getvalue()
    img = image.Image(size=(img_size[0],img_size[1]))
    img.draw_string(0, 10, err_str, scale=1, color=(0xff,0x00,0x00))
    lcd.display(img)

def main(sensor_window=(224, 224), lcd_rotation=0, sensor_hmirror=False, sensor_vflip=False):
    sensor.reset()
    sensor.set_pixformat(sensor.RGB565)
    sensor.set_framesize(sensor.QVGA)
    sensor.set_windowing((img_size[0], img_size[1]))
    sensor.set_hmirror(sensor_hmirror)
    sensor.set_vflip(sensor_vflip)

    if board_cube == 1:
        sensor.set_vflip(True)
        sensor.set_hmirror(True)
        lcd.init(type=2)
        lcd.rotation(2)
    else:
        lcd.init()
        lcd.rotation(lcd_rotation)

    sensor.run(1)
    print("Test start run")
    lcd.clear(lcd.WHITE)

    work()


def loop(uart_A=None,key_enter=1,key_back=1,key_next=1):
    try:
        img = sensor.snapshot()
        if board_cube:
            img = img.resize(img_size[0], img_size[1])
            img = img.rotation_corr(z_rotation=90)
            img.pix_to_ai()
        img.draw_string(0, 200, "hardware:grove", color=lcd.RED,scale=2)
        if not uart_A is None:
            send(uart_A,key_enter,key_back,key_next)
        img.draw_string(0, 10, "send : "+data_send, color=lcd.RED,scale=2)
        lcd.display(img)
        time.sleep_ms(100)

    except Exception as e:
        raise e
    finally:
        del img
        #pass

def work():
    try:
        uart_A = UART(UART.UART1, 115200, 8, 1, 0, timeout=1000, read_buf_len=4096)
        # reg
        fm.register(16, fm.fpioa.GPIOHS0) # 16 NEXT
        fm.register(11, fm.fpioa.GPIOHS1) #11 BACK
        fm.register(10, fm.fpioa.GPIOHS2) #10 ENTER
        key_next = GPIO(GPIO.GPIOHS0, GPIO.PULL_UP) # 0
        key_back = GPIO(GPIO.GPIOHS1, GPIO.PULL_UP) # 0
        key_enter = GPIO(GPIO.GPIOHS2, GPIO.PULL_UP) # 0

        fm.register(UART_TX, fm.fpioa.UART1_TX, force=True) # 6 24
        fm.register(UART_RX, fm.fpioa.UART1_RX, force=True) # 7 25
        time.sleep_ms(100) # wait uart ready
        
        uart_A.write(b'hello world')

        while(True):
            loop(uart_A,key_enter,key_back,key_next)
    except Exception as e:
        sys.print_exception(e)
        lcd_show_except(e)
    finally:
        fm.unregister(16)
        fm.unregister(11)
        fm.unregister(10)
        uart_A.deinit()
        del uart_A
        gc.collect()

# api
def run(uart_A=None,key_enter=1,key_back=1,key_next=1):
    try:
        global api_run
        api_run = 1
        while(api_run):
            loop(uart_A,key_enter,key_back,key_next)
    except Exception as e:
        sys.print_exception(e)
    finally:
        gc.collect()
        pass

def close():
    global api_run
    api_run = 0


def test(st):
    print("get st:",st)
    return st+"-m8"

if __name__ == "__main__":
    main()
